package br.com.websec.util;



import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

import br.com.websec.scheduler.AgendadorTarefa;
import br.com.websec.xml.RecuperaRemessaXML;
import br.com.websec.xml.RemessaXML;
import br.com.websec.xml.TituloXML;


public class ConexaoHibernateFilter implements Filter {

       private SessionFactory  sf;

       public void init(FilterConfig config) throws ServletException {
               this.sf = HibernateUtil.getSession();
       }

       public void destroy() {
       }

       public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException {

               try {

                       this.sf.getCurrentSession().beginTransaction();

                       chain.doFilter(servletRequest, servletResponse);

                       this.sf.getCurrentSession().getTransaction().commit();
                       this.sf.getCurrentSession().close();
                       

               } catch (Throwable ex) {
                       try {
                               if (this.sf.getCurrentSession().getTransaction().isActive()) {
                                       this.sf.getCurrentSession().getTransaction().rollback();
                               }
                       } catch (Throwable t) {
                               t.printStackTrace();
                       }
                       throw new ServletException(ex);
               }
               
               
               //sincronizarArquivo();
       }
       

   	public static synchronized void sincronizarArquivo() {

   		Runnable runnable = new Runnable() {

   			@Override
   			public void run() {

   				while (true) {
   					
   					try {
						Thread.sleep(20000);
						System.out.println("Foi...");
	   					//RecuperaRemessaXML.salvar();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} // 10 SEGUNDOS
   					
   					
   					

   					try {
   						Thread.sleep(10000); // 10 SEGUNDOS
   						//Thread.sleep(3600000);// 1-HORA						
   						
   					} catch (InterruptedException e) {
   						// TODO Auto-generated catch block
   						e.printStackTrace();
   					}
   				}

   			}
   		};

   		Thread thread = new Thread(runnable);

   		thread.start();
   	}


   	
   }



